package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.mapper.NurserecordMapper;
import com.neudu.yiyang.mapper.CustomerMapper;
import com.neudu.yiyang.pojo.Nurserecord;
import com.neudu.yiyang.pojo.Customer;
import com.neudu.yiyang.pojo.NurserecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class serviceCareController {

    @Autowired
    private NurserecordMapper nurserecordMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private JSONReturn jsonReturn;


    @GetMapping("/customer/list")
    public Map<String, Object> getAllCustomers() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Customer> customers = customerMapper.selectList(null);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", customers);
            return result;
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取客户列表失败: " + e.getMessage());
            return result;
        }
    }
    // 获取护理记录（分页）
    @GetMapping("/records")
    public String getNursingRecords(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String customerName) {
        try {
            // 1. 创建分页对象
            Page<NurserecordDTO> page = new Page<>(pageNum, pageSize);

            // 2. 打印调试日志（确认参数接收正确）
            System.out.println("[DEBUG] 接收查询参数 - pageNum: " + pageNum
                    + ", pageSize: " + pageSize
                    + ", customerName: " + customerName);

            // 3. 执行查询（关键修改：确保参数传递正确）
            Page<NurserecordDTO> pageResult = nurserecordMapper.selectWithCustomerForce(
                    page,
                    StringUtils.hasText(customerName) ? customerName.trim() : null
            );

            // 4. 调试日志：检查查询结果
            System.out.println("[DEBUG] 查询结果数量: " + pageResult.getRecords().size());
            if (!pageResult.getRecords().isEmpty()) {
                System.out.println("[DEBUG] 第一条记录: "
                        + "ID=" + pageResult.getRecords().get(0).getId()
                        + ", 客户名=" + pageResult.getRecords().get(0).getCustomerName());
            }

            // 5. 计算状态
            pageResult.getRecords().forEach(dto -> {
                int remaining = dto.getCurrentRemainingCount();
                dto.setStatus(
                        remaining <= 0 ? "已欠费" :
                                remaining <= 5 ? "即将用完" : "正常使用"
                );
            });

            // 6. 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", pageResult.getRecords());
            result.put("total", pageResult.getTotal());

            return jsonReturn.returnSuccess(result);

        } catch (Exception e) {
            // 7. 错误处理（增加详细日志）
            System.err.println("[ERROR] 获取护理记录失败: " + e.getMessage());
            e.printStackTrace();
            return jsonReturn.returnError("获取护理记录失败: " + e.getMessage());
        }
    }
    @PutMapping("/records/{id}")
    public String updateRecord(@PathVariable Integer id, @RequestBody NurserecordDTO dto) {
        try {
            if (id == null) {
                return jsonReturn.returnError("ID不能为空");
            }

            // 打印调试日志
            System.out.println("[DEBUG] 更新记录 - ID: " + id + ", 数据: " + dto);

            Nurserecord existing = nurserecordMapper.selectById(id);
            if (existing == null) {
                System.out.println("[ERROR] 记录不存在 - ID: " + id);
                return jsonReturn.returnError("记录不存在");
            }
            
            if (existing.getIsDeleted() == 1) {
                System.out.println("[ERROR] 记录已被删除 - ID: " + id);
                return jsonReturn.returnError("记录已被删除");
            }

            // 更新允许修改的字段
            if (dto.getNursingContent() != null) {
                existing.setNursingContent(dto.getNursingContent());
            }
            if (dto.getRemark() != null) {
                existing.setRemark(dto.getRemark());
            }
            if (dto.getLastRemainingCount() != null) {
                existing.setLastRemainingCount(dto.getLastRemainingCount());
            }
            if (dto.getPurchaseTime() != null) {
                existing.setPurchaseTime(new Date(dto.getPurchaseTime().getTime()));
            }

            int result = nurserecordMapper.updateById(existing);
            if (result > 0) {
                System.out.println("[INFO] 记录更新成功 - ID: " + id);
                return jsonReturn.returnSuccess("修改成功");
            } else {
                System.out.println("[ERROR] 记录更新失败 - ID: " + id);
                return jsonReturn.returnError("修改失败");
            }
        } catch (Exception e) {
            System.out.println("[ERROR] 更新记录异常 - ID: " + id + ", 错误: " + e.getMessage());
            e.printStackTrace();
            return jsonReturn.returnError("修改失败: " + e.getMessage());
        }
    }
    // 添加记录
    @PostMapping("/nursing/records")
    public String addRecord(@RequestBody Nurserecord record) {
        try {
            // 设置必填字段的默认值
            record.setIsDeleted(0);
            record.setItemId((int) System.currentTimeMillis());
            record.setNursingTime(new Date());
            record.setNursingCount(0);

            // 处理时间
            if (record.getPurchaseTime() != null) {
                record.setPurchaseTime(new Date(record.getPurchaseTime().getTime()));
            }

            // 计算护理项目数量
            record.setTotalCount(record.getPurchaseCount() + record.getLastRemainingCount());
            record.setCurrentRemainingCount(record.getTotalCount());
            record.setStatus("正常使用");

            record.setUserId(0);

            int result = nurserecordMapper.insert(record);
            return result > 0 ? jsonReturn.returnSuccess("添加成功") : jsonReturn.returnError("添加失败");
        } catch (Exception e) {
            return jsonReturn.returnError("添加失败: " + e.getMessage());
        }

    }
    // 删除记录（软删除）
    @DeleteMapping("/nursing/records/{id}")
    public String deleteRecord(@PathVariable Integer id) {
        try {
            Nurserecord record = nurserecordMapper.selectById(id);
            if (record == null) {
                return jsonReturn.returnError("记录不存在");
            }
            record.setIsDeleted(1); // 假设有软删除字段
            int result = nurserecordMapper.updateById(record);
            return result > 0 ? jsonReturn.returnSuccess("删除成功") : jsonReturn.returnError("删除失败");
        } catch (Exception e) {
            return jsonReturn.returnError("删除失败: " + e.getMessage());
        }
    }
    // 购买护理服务
    @PostMapping("/purchase")
    public String purchaseNursingService(@RequestBody Map<String, Object> params) {
        try {
            Integer id = (Integer) params.get("id");
            Integer purchaseCount = (Integer) params.get("purchaseCount");
            String remark = (String) params.get("remark");

            Nurserecord record = nurserecordMapper.selectById(id);
            if (record == null) {
                return jsonReturn.returnError("护理记录不存在");
            }

            // 更新记录
            record.setLastRemainingCount(record.getCurrentRemainingCount());
            record.setPurchaseCount(record.getPurchaseCount() + purchaseCount);
            record.setTotalCount(record.getTotalCount() + purchaseCount);
            record.setCurrentRemainingCount(record.getCurrentRemainingCount() + purchaseCount);
            record.setRemark(remark);
            record.setPurchaseTime(new Date());

            updateRecordStatus(record);

            int result = nurserecordMapper.updateById(record);
            if (result > 0) {
                return jsonReturn.returnSuccess("购买成功");
            } else {
                return jsonReturn.returnError("购买失败");
            }
        } catch (Exception e) {
            return jsonReturn.returnError("购买失败: " + e.getMessage());
        }
    }

    // 更新记录状态
    private void updateRecordStatus(Nurserecord record) {
        int remaining = record.getCurrentRemainingCount();
        if (remaining <= 0) {
            record.setStatus("已欠费");
        } else if (remaining <= 5) {
            record.setStatus("即将用完");
        } else {
            record.setStatus("正常使用");
        }
    }
}